//
//  LawyerListViewController.m
//  Unicorn
//
//  Created by xalo on 16/5/3.
//  Copyright © 2016年 bhj_jun. All rights reserved.
//

#import "LawyerListViewController.h"

typedef enum {
    
    proType,
    cityType
    
}Datatype;


@interface LawyerListViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong)UITableView *listtableView;
@property (nonatomic,retain)NSMutableArray *proArray; // 保存省份
@property (nonatomic,retain)NSMutableArray *cityArray;//保存城市
@property (nonatomic,retain)NSMutableArray *dataArray; // 保存律师信息
@property (nonatomic,retain)UITableView *proTableView;
@property (nonatomic,retain)UITableView *cityTableView;
@property (nonatomic,retain)UIButton *proBtn;
@property (nonatomic,retain)UIButton *cityBtn;
@property (nonatomic,retain)NSMutableDictionary *parameter;//参数
@property (nonatomic,assign)Datatype dataType;
@property (nonatomic,assign)NSInteger startInteger;

@end

@implementation LawyerListViewController

#pragma mark - 懒加载
-(UITableView *)listtableView{

    if (!_listtableView) {
        _listtableView=[[UITableView alloc]initWithFrame:CGRectMake(0,40, kWidth, kHeight-40)];
        _listtableView.delegate=self;
        _listtableView.dataSource=self;
    }
    return _listtableView;
}

-(NSMutableArray *)proArray{

    if (!_proArray) {
        _proArray=[NSMutableArray new];
    }
    return _proArray;
}


-(NSMutableArray *)cityArray{

    if (!_cityArray) {
        _cityArray=[NSMutableArray new];
    }
    return _cityArray;
}


-(NSMutableArray *)dataArray{

    if (!_dataArray) {
        _dataArray=[NSMutableArray new];
    }
    return _dataArray;
}

-(UITableView *)proTableView{

    if (!_proTableView) {
        _proTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 100, kWidth, kHeight/3*2-100)];
        _proTableView.delegate=self;
        _proTableView.dataSource=self;
    }
    return _proTableView;
}

-(UITableView *)cityTableView{

    if (!_cityTableView) {
        _cityTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 100, kWidth, kHeight/3*2-100)];
        _cityTableView.delegate=self;
        _cityTableView.dataSource=self;
    }
    return _cityTableView;
}

-(NSMutableDictionary *)parameter{

    if (!_parameter) {
        _parameter=[NSMutableDictionary dictionaryWithDictionary:@{@"dtype":@"json",@"key":@"92b2b15418072f1597cc9de8f65f5048",@"st":@(self.startInteger),@"count":@10}];
    }
    return _parameter;
}


#pragma mark - 点击方法
// 创建按钮
-(UIButton *)createButtonWithFrame:(CGRect)frame title:(NSString *)title selector:(SEL)selector{
    
    UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:title forState:UIControlStateNormal];
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    [button setFrame:frame];
    [self.view addSubview:button];
    return button;
}

// 查找省份
-(void)proClick:(UIButton *)sender{

    NSString *url=@"http://op.juhe.cn/lawyers/pros";
    [self fetchDataWithUrl:url parameter:self.parameter];
    [self.view addSubview:self.proTableView];
    self.proTableView.hidden=NO;
}

// 查找城市
-(void)cityClick:(UIButton *)sender{

    NSString *url=@"http://op.juhe.cn/lawyers/citiesByPro";
    [self.parameter setValue:self.proName forKey:@"pro"];
    [self fetchDataWithUrl:url parameter:self.parameter];
//    NSLog(@"%@",self.cityArray);
    [self.view addSubview:self.cityTableView];
    self.cityTableView.hidden=NO;
}


// 数据请求
-(void)fetchDataWithUrl:(NSString *)url parameter:(NSMutableDictionary *)parameter {
    
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    [manager GET:url parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if ([url isEqualToString:@"http://op.juhe.cn/lawyers/pros"]) {
            self.proArray=[NSMutableArray arrayWithArray:dic[@"result"]];
            [self.proTableView reloadData];
        }
        
        if ([url isEqualToString:@"http://op.juhe.cn/lawyers/citiesByPro"]) {
            self.cityArray=[NSMutableArray arrayWithArray:dic[@"result"]];
              [self.cityTableView reloadData];
        }
        if ([url isEqualToString:@"http://op.juhe.cn/lawyers/rand"] || [url isEqualToString:@"http://op.juhe.cn/lawyers/pro"] || [url isEqualToString:@"http://op.juhe.cn/lawyers/city"]) {
            NSArray *resultArray=dic[@"result"];
            for (NSDictionary *mDic in resultArray) {
                LawyerModel *model=[[LawyerModel alloc]init];
                [model setValuesForKeysWithDictionary:mDic];
                [self.dataArray addObject:model];
            }
             [self.listtableView reloadData];
            // 结束上拉加载下拉刷新
            [self.listtableView.mj_header endRefreshing];
            [self.listtableView.mj_footer endRefreshing];
        }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"数据请求失败");
    }];
}

// 按省份查找律师
-(void)findLawyerWithProvinceName:(NSString *)proName{

    [self.parameter setValue:proName forKey:@"pro"];
    [self.parameter setValue:@0 forKey:@"st"];
    [self.parameter setValue:@10 forKey:@"count"];
    NSString *url=@"http://op.juhe.cn/lawyers/pro";
    [self fetchDataWithUrl:url parameter:self.parameter];
}

// 按城市查找律师
-(void)findLawyerWithCityName:(NSString *)cityName{

    [self.parameter setValue:cityName forKey:@"city"];
    [self.parameter setValue:@0 forKey:@"st"];
    [self.parameter setValue:@10 forKey:@"count"];
    NSString *url=@"http://op.juhe.cn/lawyers/city";
    [self fetchDataWithUrl:url parameter:self.parameter];
}


#pragma mark - 视图生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title=@"律师";
    [self.view addSubview:self.listtableView];
    self.startInteger=0;
    // 创建按钮
    self.proBtn= [self createButtonWithFrame:CGRectMake(0, 64, kWidth/2, 40) title:[NSString stringWithFormat:@"[s]%@",self.proName] selector:@selector(proClick:)];
    self.proBtn.backgroundColor=[UIColor cyanColor];
    self.cityBtn=[self createButtonWithFrame:CGRectMake(kWidth/2, 64, kWidth/2, 40) title:[NSString stringWithFormat:@"[c]%@",self.cityName] selector:@selector(cityClick:)];
    self.cityBtn.backgroundColor=[UIColor cyanColor];
    // 注册单元格
    [self.listtableView registerNib:[UINib nibWithNibName:@"LawyerCell" bundle:nil] forCellReuseIdentifier:@"LawyerCell"];
    [self.proTableView registerNib:[UINib nibWithNibName:@"LawyerCell" bundle:nil] forCellReuseIdentifier:@"LawyerCell"];
    [self.cityTableView registerNib:[UINib nibWithNibName:@"LawyerCell" bundle:nil] forCellReuseIdentifier:@"LawyerCell"];
    ///
    NSString *url=@"http://op.juhe.cn/lawyers/rand";
    [self fetchDataWithUrl:url parameter:self.parameter];
      // 上拉加载下拉刷新
    [self downLoadWithMoveUpAnDown];
    
    // Do any additional setup after loading the view.
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (tableView==self.proTableView) {
        return self.proArray.count;
    }
   else if (tableView==self.cityTableView) {
        return self.cityArray.count;
    }else{
        return self.dataArray.count;
    }
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LawyerCell *cell=[tableView dequeueReusableCellWithIdentifier:@"LawyerCell" forIndexPath:indexPath];
    if (tableView==self.proTableView) {
        
        cell.textLabel.text=self.proArray[indexPath.row];
        
        cell.name.hidden=YES;
        cell.province.hidden=YES;
        cell.cityLabel.hidden=YES;
        cell.telLabel.hidden=YES;
        cell.specialty.hidden=YES;
        cell.headImage.hidden=YES;
        cell.pro.hidden=YES;
        cell.city.hidden=YES;
        cell.spe.hidden=YES;
        cell.tel.hidden=YES;
        cell.namelabel.hidden=YES;
    }else if (tableView==self.cityTableView){
        
        cell.textLabel.text=self.cityArray[indexPath.row];
        
        cell.name.hidden=YES;
        cell.province.hidden=YES;
        cell.cityLabel.hidden=YES;
        cell.telLabel.hidden=YES;
        cell.specialty.hidden=YES;
        cell.headImage.hidden=YES;
        cell.pro.hidden=YES;
        cell.city.hidden=YES;
        cell.spe.hidden=YES;
        cell.tel.hidden=YES;
        cell.namelabel.hidden=YES;
    }
    else{
        LawyerModel *model=self.dataArray[indexPath.row];
        [cell setCellWithModel:model];
    }
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.proTableView) {
        self.proName=self.proArray[indexPath.row];
        [self.proBtn setTitle:self.proName forState:UIControlStateNormal];
        [self findLawyerWithProvinceName:self.proArray[indexPath.row]];
        self.proTableView.hidden=YES;
    }else if(tableView==self.cityTableView){
        self.cityName=self.cityArray[indexPath.row];
        [self.cityBtn setTitle:self.cityName forState:UIControlStateNormal];
        [self findLawyerWithCityName:self.cityArray[indexPath.row]];
        self.cityTableView.hidden=YES;
    }
    else{
        
        LawyerDetailViewController *detailVC=[[UIStoryboard storyboardWithName:@"Lawyer" bundle:nil]instantiateViewControllerWithIdentifier:@"LawyerVC"];
        detailVC.model=self.dataArray[indexPath.row];
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (tableView==self.listtableView) {
        return 150;
    }else{
        return 50;
    }
 }
#pragma mark - 上拉加载，下拉刷新
-(void)downLoadWithMoveUpAnDown{
    
    //////////////////   下拉刷新      ////////////////////
    self.listtableView.mj_header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.dataArray=nil;
        self.startInteger=0;
        [self.parameter setValue:[NSNumber numberWithInteger:self.startInteger] forKey:@"st"];
        [self fetchDataWithUrl:@"http://op.juhe.cn/lawyers/rand" parameter:self.parameter];
    }];
    
        ////////////////////////  上拉加载  ////////////////////
    self.listtableView.mj_footer=[MJRefreshBackFooter footerWithRefreshingBlock:^{
        
        self.startInteger+=10;
        [self.parameter setValue:[NSNumber numberWithInteger:self.startInteger] forKey:@"st"];
        [self.parameter setValue:@"addtime" forKey:@"sort"];
        [self fetchDataWithUrl:@"http://op.juhe.cn/lawyers/rand" parameter:self.parameter];
    }];
}


@end
